package com.agileai.portal.portlets.wcmlist;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;
import javax.servlet.http.HttpServletRequest;

import org.apache.pluto.container.PortletRequestContext;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataRow;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.portal.bizmoduler.wcm.InfomationManage;
import com.agileai.portal.driver.AttributeKeys;
import com.agileai.portal.driver.GenericPotboyPortlet;
import com.agileai.portal.driver.Resource;
import com.agileai.portal.driver.common.PortletRequestHelper;
import com.agileai.portal.driver.common.PortletVariableHelper;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.driver.model.Theme;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class InfomationGrid extends GenericPotboyPortlet {
	@RenderMode(name = "view")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);
		String templateId = preferences.getValue("templateId", null);
		String minHeight = preferences.getValue("minHeight", null);
		String sortPolicy = preferences.getValue("sortPolicy", null);
		String columnIdParamKey = preferences.getValue("columnIdParamKey", null);
		String infoLinkURL = preferences.getValue("infoLinkURL", null);
		
		String recCountPerPage = preferences.getValue("recCountPerPage",null);
		String mainNumCount = preferences.getValue("mainNumCount", null);
		String sideNumCount = preferences.getValue("sideNumCount", null);
		
		if (!StringUtil.isNullOrEmpty(templateId) && !StringUtil.isNullOrEmpty(sortPolicy) 
				&& !StringUtil.isNullOrEmpty(minHeight)
				&& !StringUtil.isNullOrEmpty(infoLinkURL)
				&& !StringUtil.isNullOrEmpty(recCountPerPage) 
				&& !StringUtil.isNullOrEmpty(mainNumCount) 
				&& !StringUtil.isNullOrEmpty(sideNumCount)
				&& !StringUtil.isNullOrEmpty(columnIdParamKey)
				){
			request.setAttribute("isSetting", "Y");
		}else{
			request.setAttribute("isSetting", "N");
		}
		
		String isSetting = (String)request.getAttribute("isSetting");
		if ("Y".equals(isSetting)){
			request.setAttribute("recCountPerPage", recCountPerPage);
			request.setAttribute("minHeight", minHeight);
			request.setAttribute("mainNumCount", mainNumCount);
			request.setAttribute("sideNumCount", sideNumCount);
			request.setAttribute("portletId", request.getWindowID());
			
			PortletRequestContext portletRequestContext = PortletRequestHelper.getRequestContext(request);
			HttpServletRequest httpServletRequest = portletRequestContext.getServletRequest();
			Theme theme = (Theme)httpServletRequest.getAttribute(AttributeKeys.THEME_KEY);
			request.setAttribute("themeType", theme.getType());
		}
		super.doView(request, response);
	}
	
	private String getURLPrefix(PortletRequest request,String themeType){
		String result = null;
		if (Theme.Type.LOGIN_BEFORE.equals(themeType)){
			result = request.getContextPath()+"/website/";
		}else{
			result = request.getContextPath()+"/request/";
		}
		return result;
	}
	
	private String retrieveData(PortletPreferences preferences,String dataURL) throws Exception{
		String ajaxData = "";
		String cacheMinutes = (String)preferences.getValue("cacheMinutes",defaultCacheMinutes);
		String isCache = preferences.getValue("isCache", defaultIsCache);
		ajaxData = PortletCacheManager.getOnly().getCachedData(isCache, dataURL, cacheMinutes);
		return ajaxData;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void generate(InfomationsModel infoListModel,String template,StringWriter writer) {
		String encoding = "utf-8";
		try {
        	Configuration cfg = new Configuration();
        	cfg.setTemplateLoader(new StringTemplateLoader(template));  
        	cfg.setEncoding(Locale.getDefault(), encoding);
            cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        	Template temp = cfg.getTemplate("");
        	temp.setEncoding(encoding);
            Map root = new HashMap();
            root.put("model",infoListModel);
            temp.process(root, writer);
            writer.flush();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	@RenderMode(name = "edit")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String templateId = preferences.getValue("templateId", null);
		String minHeight = preferences.getValue("minHeight", "400");
		String sortPolicy = preferences.getValue("sortPolicy", InfomationManage.SortPolicy.PublishTimeDesc);
		String columnIdParamKey = preferences.getValue("columnIdParamKey", "columnId");
		String columnIdDefValue = preferences.getValue("columnIdDefValue", null);
		String infoLinkURL = preferences.getValue("infoLinkURL", null);
		String recCountPerPage = preferences.getValue("recCountPerPage", "20");
		String maxCharNumber = preferences.getValue("maxCharNumber", "30");
		String mainNumCount = preferences.getValue("mainNumCount", "10");
		String sideNumCount = preferences.getValue("sideNumCount", "2");
		
		String isCache = preferences.getValue("isCache", defaultIsCache);
		String cacheMinutes = preferences.getValue("cacheMinutes", defaultCacheMinutes);
		
		request.setAttribute("templateId", templateId);
		request.setAttribute("minHeight", minHeight);
		request.setAttribute("columnIdParamKey", columnIdParamKey);
		request.setAttribute("columnIdDefValue", columnIdDefValue);
		request.setAttribute("infoLinkURL", infoLinkURL);
		request.setAttribute("sortPolicy", sortPolicy);
		
		request.setAttribute("recCountPerPage", recCountPerPage);
		request.setAttribute("mainNumCount", mainNumCount);
		request.setAttribute("sideNumCount", sideNumCount);
		request.setAttribute("maxCharNumber", maxCharNumber);
		
		request.setAttribute("isCache", isCache);
		request.setAttribute("cacheMinutes", cacheMinutes);
		
		super.doEdit(request, response);
	}

	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException,
			IOException, PreferenceException {
		String templateId = request.getParameter("templateId");
		String minHeight = request.getParameter("minHeight");
		String sortPolicy = request.getParameter("sortPolicy");
		String columnIdParamKey = request.getParameter("columnIdParamKey");
		String columnIdDefValue = request.getParameter("columnIdDefValue");
		
		String infoLinkURL = request.getParameter("infoLinkURL");
		
		String recCountPerPage = request.getParameter("recCountPerPage");
		String mainNumCount = request.getParameter("mainNumCount");
		String sideNumCount = request.getParameter("sideNumCount");
		String maxCharNumber = request.getParameter("maxCharNumber");
		
		String isCache = request.getParameter("isCache");
		String cacheMinutes = request.getParameter("cacheMinutes");
		
		PreferencesWrapper preferWapper = new PreferencesWrapper();		
		preferWapper.setValue("templateId", templateId);
		preferWapper.setValue("minHeight", minHeight);
		preferWapper.setValue("sortPolicy", sortPolicy);
		preferWapper.setValue("columnIdParamKey", columnIdParamKey);
		preferWapper.setValue("columnIdDefValue", columnIdDefValue);
		
		preferWapper.setValue("infoLinkURL", infoLinkURL);
		
		preferWapper.setValue("recCountPerPage", recCountPerPage);
		preferWapper.setValue("mainNumCount", mainNumCount);
		preferWapper.setValue("sideNumCount", sideNumCount);
		preferWapper.setValue("maxCharNumber", maxCharNumber);
		
		preferWapper.setValue("isCache", isCache);
		preferWapper.setValue("cacheMinutes", cacheMinutes);
		
		PreferencesHelper.savePublicPreferences(request, preferWapper.getPreferences());	
		response.setPortletMode(PortletMode.VIEW);
	}
	
	
	@Resource(id="getRecordCount")
	public void getRecordCount(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String ajaxData = "";
		try {
			PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
			String columnIdParamKey = preferences.getValue("columnIdParamKey", null);
			String columnIdDefValue = preferences.getValue("columnIdDefValue", null);
			
			PortletVariableHelper portletVariableHelper = null;
			if (StringUtil.isNullOrEmpty(columnIdDefValue)){
				portletVariableHelper = new PortletVariableHelper(request);	
			}else{
				String defalultString = columnIdParamKey+"="+columnIdDefValue;
				portletVariableHelper = new PortletVariableHelper(request,defalultString);
			}
			String columnId = portletVariableHelper.getRealValue(columnIdParamKey);
			String sortPolicy = preferences.getValue("sortPolicy", null);
			
			String urlPrefix = PortletCacheManager.buildDataURLPefix(request);
			String sessionId = request.getPortletSession().getId();
			String dataURL = urlPrefix+"/resource;jsessionid="+sessionId+"?ContentProvider&actionType=findInfomationGrid&columnId="+columnId+"&sortPolicy="+sortPolicy;
			String jsonData = this.retrieveData(preferences, dataURL);
			if (jsonData != null && jsonData.length() > 1){
				JSONObject jsonObject = new JSONObject(jsonData);
				int length = jsonObject.length();
				if (length > 0){
					JSONArray jsonArray = jsonObject.getJSONArray("infomations");
					if (jsonArray != null && jsonArray.length() > 0){
						ajaxData = String.valueOf(jsonArray.length());
					}
				}else{
					ajaxData = "0";
				}
			}	
		} catch (Exception e) {
			this.logger.error("获取取数据失败getRecordCount", e);
		}
		PrintWriter writer = response.getWriter();
		writer.print(ajaxData);
		writer.close();
	}
	
	@Resource(id="getAjaxData")
	public void getAjaxData(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String ajaxData = "";
		try {
			PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
			String columnIdParamKey = preferences.getValue("columnIdParamKey", null);
			String columnIdDefValue = preferences.getValue("columnIdDefValue", null);
			
			PortletVariableHelper portletVariableHelper = null;
			if (StringUtil.isNullOrEmpty(columnIdDefValue)){
				portletVariableHelper = new PortletVariableHelper(request);	
			}else{
				String defalultString = columnIdParamKey+"="+columnIdDefValue;
				portletVariableHelper = new PortletVariableHelper(request,defalultString);
			}
			String columnId = portletVariableHelper.getRealValue(columnIdParamKey);
			
			String templateId = preferences.getValue("templateId", null);
			String sortPolicy = preferences.getValue("sortPolicy", null);
			String infoLinkURL = preferences.getValue("infoLinkURL", null);
			String maxCharNumber = preferences.getValue("maxCharNumber", "30");
			String themeType = request.getParameter("themeType");
			
			String urlPrefix = PortletCacheManager.buildDataURLPefix(request);
			String sessionId = request.getPortletSession().getId();
			String dataURL = urlPrefix+"/resource;jsessionid="+sessionId+"?ContentProvider&actionType=findInfomationGrid&columnId="+columnId+"&sortPolicy="+sortPolicy;
			String jsonData = this.retrieveData(preferences, dataURL);
			if (jsonData != null && jsonData.length() > 1){
				JSONObject jsonObject = new JSONObject(jsonData);
				String likeUrlPrefix = getURLPrefix(request,themeType);
				if (jsonObject.length() > 0){
					InfomationsModel infoListModel = new InfomationsModel();
					infoListModel.setColumnId(columnId);
					infoListModel.setColumnName(jsonObject.getString("columnName"));
					infoListModel.setColumnTitle(jsonObject.getString("columnTitle"));
					infoListModel.setInfoLinkURL(likeUrlPrefix + infoLinkURL);
					JSONArray jsonArray = jsonObject.getJSONArray("infomations");
					if (jsonArray != null && jsonArray.length() > 0){
						int startIndex = Integer.parseInt(request.getParameter("startIndex"));
						int endIndex = Integer.parseInt(request.getParameter("endIndex"));
						for (int i=startIndex;i < endIndex;i++){
							JSONObject tempJsonObject = (JSONObject)jsonArray.get(i);
							DataRow row = new DataRow();			
							infoListModel.getRecordList().add(row);
							row.put("id",tempJsonObject.get("id"));
							row.put("title",tempJsonObject.get("title"));
							row.put("outline",tempJsonObject.get("outline"));
							String shortTitle = (String)tempJsonObject.get("shortTitle");
							row.put("shortTitle",this.substring(shortTitle, maxCharNumber));
							
							row.put("readCount",tempJsonObject.get("readCount"));
							row.put("publishTime",tempJsonObject.get("publishTime"));
						}
					}
					StringWriter writer = new StringWriter();
					String tempateURL = urlPrefix+"/resource?PortletTemptProvider&actionType=retrieveContent&contentId="+templateId;
					String template = this.retrieveData(preferences, tempateURL);
					generate(infoListModel, template, writer);
					ajaxData = writer.toString();					
				}
			}
		} catch (Exception e) {
			this.logger.error("获取取数据失败getAjaxData", e);
		}
		PrintWriter writer = response.getWriter();
		writer.print(ajaxData);
		writer.close();
	}
	private String substring(String value ,String lenghtLimit){
		String result = value;
		if (value != null && value.length() > Integer.parseInt(lenghtLimit)){
			result = value.substring(0,Integer.parseInt(lenghtLimit))+"…";
		}
		return result;
	}
}
